package gui;

import database.*;

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.util.List;


public class PanelBestillRett extends JPanel implements ActionListener {
	private JScrollPane scrollPaneMeny, scrollPaneBestilling;
	private DefaultTableModel tableModelMeny, tableModelBestilling;
	private JTable tabellMeny, tabellBestilling;
	private JLabel labelKunde, labelNavn, labelAdresse, labelTelefon, labelPost,  labelMeny, labelBestilling, labelPrisUMva, labelPrisMMva;
	private JButton  buttonOK, buttonHovedmeny, buttonLeggTil, buttonFjern;
	private Vector<String> kolonnenavnMeny, kolonnenavnBestilling;
	private GridBagConstraints constraints;
	private Kunde kunde;
	private Bestilling bestilling = null;
	private List<Rett> retter;
	private double prisUMva, prisMMva;
	
	public PanelBestillRett(Kunde kunde){
		this.kunde = kunde;
		this.setLayout(new GridBagLayout());
		this.leggTilKomponenter();
		GUI.getVindu().add(this);
		
	}
	public PanelBestillRett(Bestilling bestilling){
		this.bestilling = bestilling;
		this.kunde = Register.findKundeObjekt(bestilling.getKundeID());
		this.retter = Register.findRetter(bestilling);
		this.setLayout(new GridBagLayout());
		this.leggTilKomponenter();
		GUI.getVindu().add(this);
		fyllTableModelBestilling();
		endrePriser();
	}
	public PanelBestillRett(Kunde kunde, List<Rett> retter){
		this.kunde = kunde;
		this.retter = retter;
		this.setLayout(new GridBagLayout());
		this.leggTilKomponenter();
		GUI.getVindu().add(this);
		fyllTableModelBestilling();
		endrePriser();
		
	}
	
	private void fyllTableModelBestilling() {
		boolean eksisterer;
		for (int i = 0; i < retter.size(); i++) {
			eksisterer = false;
			for (int j = 0; j < tabellBestilling.getRowCount(); j++) {
				if(retter.get(i).getVareID()==Integer.parseInt((String)tabellBestilling.getValueAt(j, 0))){
					tabellBestilling.setValueAt(""+(Integer.parseInt((String)tabellBestilling.getValueAt(j, 4))+1), j, 4);
					eksisterer = true;
					
				}
			}
			if(!eksisterer){
				Vector<String> radData = new Vector<String>();
				radData.add(Integer.toString(retter.get(i).getVareID()));
				radData.add(retter.get(i).getNavn());
				radData.add(Integer.toString(retter.get(i).getPris()));
				radData.add(retter.get(i).getBeskrivelse());
				radData.add("1");
				tableModelBestilling.addRow(radData);
			}
			prisUMva += retter.get(i).getPris(); 
		}
		
	}
	private void leggTilKomponenter(){
		kolonnenavnMeny = getKolonnenavnMeny();
		tableModelMeny = new DefaultTableModel(kolonnenavnMeny,0){
			@Override
			public boolean isCellEditable(int row, int column) {
			       //all cells false
			       return false;
			}
		};
		fyllTableModelMeny();
		
		kolonnenavnBestilling = getKolonnenavnBestilling();
		tableModelBestilling = new DefaultTableModel(kolonnenavnBestilling,0){
			@Override
			public boolean isCellEditable(int row, int column) {
			       //all cells false
			       return false;
			}
		};
		
		labelKunde = new JLabel("Kunde");
		Font font = new Font(labelKunde.getFont().getFontName(),labelKunde.getFont().getStyle(),30);
		labelKunde.setFont(font);
		font = new Font(labelKunde.getFont().getFontName(),labelKunde.getFont().getStyle(),20);
		labelNavn = new JLabel("Navn: " + kunde.getfNavn() + " " + kunde.geteNavn());
		labelNavn.setFont(font);
		labelAdresse = new JLabel("Adresse: " + kunde.getAdresse());
		labelAdresse.setFont(font);
		labelPost = new JLabel("" + kunde.getPostNr() + " " + Register.getPostSted(kunde.getPostNr()));
		labelPost.setFont(font);
		labelTelefon = new JLabel("Telefon: " + kunde.getTlf());
		labelTelefon.setFont(font);
		labelMeny = new JLabel("Meny");
		labelMeny.setFont(font);
		labelBestilling = new JLabel("Bestilling");
		labelBestilling.setFont(font);
	
		labelPrisUMva = new JLabel("Pris uten moms: ");
		labelPrisMMva = new JLabel("Pris med moms: ");
		

		
		buttonLeggTil = new JButton("Legg til");
		buttonLeggTil.setEnabled(false);
		buttonLeggTil.addActionListener(this);
		
		buttonHovedmeny = new JButton("Tilbake til hovedmeny");
		buttonHovedmeny.addActionListener(this);

		buttonOK = new JButton("OK");
		buttonOK.setEnabled(false);
		buttonOK.addActionListener(this);

		buttonFjern = new JButton("Fjern");
		buttonFjern.setEnabled(false);
		buttonFjern.addActionListener(this);
		

		
		tabellMeny = new JTable(tableModelMeny);
		tabellMeny.getColumnModel().getColumn(3).setPreferredWidth(100);
		tabellMeny.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		tabellMeny.setMinimumSize(new Dimension(400,600));
		ListSelectionModel rad = tabellMeny.getSelectionModel();
		rad.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				radMenySelected(e);
				
			}
		});
		tabellMeny.getColumnModel().getColumn(0).setPreferredWidth(50);
		tabellMeny.getColumnModel().getColumn(1).setPreferredWidth(80);
		tabellMeny.getColumnModel().getColumn(2).setPreferredWidth(50);
		tabellMeny.getColumnModel().getColumn(3).setPreferredWidth(240);
		
		tabellBestilling = new JTable(tableModelBestilling);
		tabellBestilling.getColumnModel().getColumn(3).setPreferredWidth(100);
		tabellBestilling.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		ListSelectionModel radBestilling = tabellBestilling.getSelectionModel();
		radBestilling.addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				radBestillingSelected(e);
				
			}

			
		});
		tabellBestilling.getColumnModel().getColumn(0).setPreferredWidth(50);
		tabellBestilling.getColumnModel().getColumn(1).setPreferredWidth(80);
		tabellBestilling.getColumnModel().getColumn(2).setPreferredWidth(50);
		tabellBestilling.getColumnModel().getColumn(3).setPreferredWidth(200);
		tabellBestilling.getColumnModel().getColumn(4).setPreferredWidth(50);
		
		scrollPaneMeny = new JScrollPane(tabellMeny);
		scrollPaneMeny.setMinimumSize(new Dimension(600, 400));
		scrollPaneMeny.setPreferredSize(new Dimension(600, 400));
		scrollPaneBestilling = new JScrollPane(tabellBestilling);
		scrollPaneBestilling.setMinimumSize(new Dimension(600, 400));
		scrollPaneBestilling.setPreferredSize(new Dimension(600, 400));
		
		
		constraints = new GridBagConstraints();
		constraints.insets = new Insets(10, 10, 10, 10);
		constraints.weightx = 1;
		constraints(0, 0);
		constraints.gridwidth = 2;
		this.add(labelKunde,constraints);
		constraints.gridwidth = 1;
		constraints(0, 1);
		constraints.anchor = GridBagConstraints.LINE_END;
		this.add(labelNavn,constraints);
		constraints(1, 1);
		constraints.anchor = GridBagConstraints.LINE_START;
		this.add(labelTelefon,constraints);
		constraints.anchor = GridBagConstraints.CENTER;
		constraints(0, 2);
		this.add(labelMeny,constraints);
		constraints(0, 3, 1, 7, 1, 0);
		this.add(scrollPaneMeny,constraints);
		constraints(0, 10, 1, 1, 1, 0);
		this.add(buttonLeggTil,constraints);
		constraints(1, 2);
		this.add(labelBestilling,constraints);
		constraints(1, 3, 1, 7, 1, 0);
		this.add(scrollPaneBestilling,constraints);
		constraints(1, 10, 1, 1, 1, 0);
		this.add(buttonFjern,constraints);
		constraints(0, 11);
		constraints.anchor = GridBagConstraints.LINE_END;
		this.add(buttonOK,constraints);
		constraints(1, 11);
		constraints.anchor = GridBagConstraints.LINE_START;
		this.add(buttonHovedmeny,constraints);

		constraints(2, 1, 1, 1, 1, 0);
		this.add(labelPrisUMva, constraints);
		constraints(2, 2, 1, 1, 1, 0);
		this.add(labelPrisMMva, constraints);
	}


	private void constraints(int gridx, int gridy,int gridwidth, int gridheight, double weightx, double weighty ){
		constraints.gridx = gridx;
		constraints.gridy = gridy;
		constraints.gridwidth = gridwidth;
		constraints.gridheight = gridheight;
		constraints.weightx = weightx;
		constraints.weighty = weighty;
	}
	private void constraints(int gridx, int gridy){
		constraints.gridx = gridx;
		constraints.gridy = gridy;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==buttonHovedmeny)
			buttonHovedmeny_actionPerformed(e);
		else if(e.getSource()==buttonOK)
			buttonOK_actionPerformed(e);
		else if(e.getSource()==buttonLeggTil)
			buttonLeggTil_actionPerformed(e);
		else if(e.getSource()==buttonFjern)
			buttonFjern_actionPerformed(e);
	
	}

	private void radMenySelected(ListSelectionEvent e){
		
		if (tabellMeny.getSelectedRows().length == 0) {
	        //No selection, disable fire button.
	            buttonLeggTil.setEnabled(false);

	        } else {
	        //Selection, enable the fire button.
	            buttonLeggTil.setEnabled(true);
	        }
		
		
		
	}
	private void radBestillingSelected(ListSelectionEvent e) {
		if (tabellBestilling.getSelectedRows().length == 0) {
	        //No selection, disable fire button.
	            buttonFjern.setEnabled(false);

	        } else {
	        //Selection, enable the fire button.
	            buttonFjern.setEnabled(true);
	        }
		
	}
	private void buttonOK_actionPerformed(ActionEvent e) 
	{

		List<Rett> retter = new ArrayList<Rett>();
		for (int i = 0; i < tabellBestilling.getRowCount(); i++) {
			for (int j = 0; j < Integer.parseInt((String)tabellBestilling.getValueAt(i, 4)); j++) {
				retter.add(Register.findRettObjekt(Integer.parseInt((String)tabellBestilling.getValueAt(i,0))));
			}
				
		}
		
		if(bestilling==null){
			this.setVisible(false);
			new PanelBestillingLevering(kunde,retter);
		}
		else{
			this.setVisible(false);
			Databasecon.updateBestillingRetter(bestilling, retter);
			new PanelBestillingLevering(kunde,retter);
		}
			
	}


	private void buttonHovedmeny_actionPerformed(ActionEvent e)
	{
		this.setVisible(false);
		new PanelHovedmeny();
	}
	private void buttonFjern_actionPerformed(ActionEvent e) {
		int[] retter = tabellBestilling.getSelectedRows();
		List<Rett> retter2 = new ArrayList<Rett>();
		for (int i = 0; i < retter.length; i++) {
			retter2.add(Register.findRett((String) tabellBestilling.getValueAt(retter[i], 1)));
		}
		for (int i = 0; i < retter2.size(); i++) {
			for (int j = 0; j < tabellBestilling.getRowCount(); j++) {
				if(retter2.get(i).getVareID()==Integer.parseInt((String)tabellBestilling.getValueAt(j, 0))){
					if(Integer.parseInt((String)tabellBestilling.getValueAt(j, 4))>1){
						tabellBestilling.setValueAt(""+(Integer.parseInt((String)tabellBestilling.getValueAt(j, 4))-1), j, 4);
					}
					else{
						tableModelBestilling.removeRow(j);
					}
					
				}
			}
			prisUMva -= retter2.get(i).getPris();
		}
		tabellBestilling.removeRowSelectionInterval(0,tabellBestilling.getRowCount()-1);
		if(tabellBestilling.getRowCount()==0){
			buttonOK.setEnabled(false);
		}
		endrePriser();
		
	}
	private void buttonLeggTil_actionPerformed(ActionEvent e) {
		boolean eksisterer;
		int[] retter = tabellMeny.getSelectedRows();
		List<Rett> retter2 = new ArrayList<Rett>();
		for (int i = 0; i < retter.length; i++) {
			retter2.add(Register.findRett((String) tabellMeny.getValueAt(retter[i], 1)));
		}
		for (int i = 0; i < retter2.size(); i++) {
			eksisterer = false;
			for (int j = 0; j < tabellBestilling.getRowCount(); j++) {
				if(retter2.get(i).getVareID()==Integer.parseInt((String)tabellBestilling.getValueAt(j, 0))){
					tabellBestilling.setValueAt(""+(Integer.parseInt((String)tabellBestilling.getValueAt(j, 4))+1), j, 4);
					eksisterer = true;
					
				}
			}
			if(!eksisterer){
				Vector<String> radData = new Vector<String>();
				radData.add(Integer.toString(retter2.get(i).getVareID()));
				radData.add(retter2.get(i).getNavn());
				radData.add(Integer.toString(retter2.get(i).getPris()));
				radData.add(retter2.get(i).getBeskrivelse());
				radData.add("1");
				tableModelBestilling.addRow(radData);
			}
			prisUMva += retter2.get(i).getPris(); 
		}
		tabellMeny.removeRowSelectionInterval(0,tableModelMeny.getRowCount()-1);
		buttonOK.setEnabled(true);
		endrePriser();
		
	}

	private Vector<String> getKolonnenavnMeny(){
		Vector<String> kolonnenavn = new Vector<String>();
		kolonnenavn.add("Nummer");
		kolonnenavn.add("Navn");
		kolonnenavn.add("Pris");
		kolonnenavn.add("Beskrivelse");
		return kolonnenavn;
	}
	
	private Vector<String> getKolonnenavnBestilling() {
		Vector<String> kolonnenavn = new Vector<String>();
		kolonnenavn.add("Nummer");
		kolonnenavn.add("Navn");
		kolonnenavn.add("Pris");
		kolonnenavn.add("Beskrivelse");
		kolonnenavn.add("Antall");
		return kolonnenavn;
	}
	
	private void fyllTableModelMeny(){
		List<Rett> retter = Databasecon.getMeny();
		for (int i = 0; i < retter.size(); i++) {
			Vector<String> radData = new Vector<String>();
			radData.add(Integer.toString(retter.get(i).getVareID()));
			radData.add(retter.get(i).getNavn());
			radData.add(Integer.toString(retter.get(i).getPris()));
			radData.add(retter.get(i).getBeskrivelse());
			tableModelMeny.addRow(radData);
		}
		
	}
	private void endrePriser(){
		DecimalFormat f;
		f = new DecimalFormat("0.00");
		labelPrisUMva.setText("Pris uten moms: " + f.format(prisUMva) + " kr.");
		prisMMva = prisUMva*1.12;
		labelPrisMMva.setText("Pris med moms: " + f.format(prisMMva) + " kr.");
	}


}